package com.woniu.day8.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.day8.mapper.MenuMapper;
import com.woniu.day8.pojo.Menu;
import com.woniu.day8.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> queryAllMenu(){
        List<Menu> list = menuMapper.selectList( null);
        // 格式化菜单
        // 找出所有一级菜单
        List<Menu> onelist = new ArrayList<>();
        for (Menu menu : list) {
            if (menu.getPid() == 0) {
                onelist.add(menu);
            }
        }
        // 根据一级菜单找出对应子菜单
        for (Menu menu : onelist) {
            menu.setChildren(getChildren(menu.getMid(), list));
        }
        return onelist;
    }
    @Override
    public List<Menu> SelectMenu(Integer id) {
        List<Menu> menus = menuMapper.SelectMenu(id);
        // 格式化菜单
        // 找出所有一级菜单
        List<Menu> onelist = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getPid() == 0) {
                onelist.add(menu);
            }
        }
        // 根据一级菜单找出对应子菜单
        for (Menu menu : onelist) {
            menu.setChildren(getChildren(menu.getMid(), menus));
        }
        return onelist;
    }

    // 递归
    private List<Menu> getChildren(Integer parentId, List<Menu> menus) {
        List<Menu> children = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getPid()==parentId) {
                children.add(menu);
            }
        }
        // 为每个子菜单也查找其子菜单
        for (Menu childMenu : children) {
            childMenu.setChildren(getChildren(childMenu.getMid(), menus));
        }

        return children;
    }

}
